//
//  RTCWebSocketManager.m
//  YouinRTC
//
//  Created by 潘欣 on 2022/8/20.
//

#import "RTCWebSocketManager.h"

@implementation RTCWebSocketManager

#pragma mark -- WebSocket

//初始化 WebSocket
- (void)initWebSocket{
    if (_socket) {
        return;
    }
    _isReconnected = true;
    //Url
    NSURL *url = [NSURL URLWithString:self.serverURL];
    //请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //初始化请求`
    //_socket = [[SRWebSocket alloc] initWithURLRequest:request];
    _socket = [[SRWebSocket alloc] initWithURL:url];
    //代理协议`
    _socket.delegate = self;
    // 实现这个 SRWebSocketDelegate 协议啊`
    //直接连接`
        // open 就是直接连接了
    if(_netWorkManager == nil){
        _netWorkManager = [AFNetworkReachabilityManager sharedManager];
        [_netWorkManager startMonitoring];
        [_netWorkManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case AFNetworkReachabilityStatusUnknown:
                    
                    self.isReconnected = true;
                    [self reConnect];
                    break;
                case AFNetworkReachabilityStatusNotReachable:
                    self.isReconnected = false;
                    break;
                case AFNetworkReachabilityStatusReachableViaWWAN:
                    self.isReconnected = true;
                    [self reConnect];
                    break;
                case AFNetworkReachabilityStatusReachableViaWiFi:
                    self.isReconnected = true;
                    [self reConnect];
                    break;
                default:
                    break;
            }
        }];
    }
    
}

-(void)close{
    [_socket closeWithCode:@0 reason:nil];
}
//断开连接时销毁心跳
//- (void)destoryHeart{
//
//    if (self.heatBeat) {
//        [self.heatBeat invalidate];
//        self.heatBeat = nil;
//    }
//}
#pragma mark -- SRWebSocketDelegate
//收到服务器消息是回调
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{
    
}

-(void)send:(NSString *)message{
    if(self.isConnected){
        [self.socket send:message];
    }
}

//连接成功
- (void)webSocketDidOpen:(SRWebSocket *)webSocket{
    
    //[self initHeart];
    
    
    if (self.socket != nil) {
        // 只有 SR_OPEN 开启状态才能调 send 方法啊，不然要崩
        if (_socket.readyState == SR_OPEN) {
            self.isConnected = YES;
            if([self.delegate respondsToSelector:@selector(socketConnect)]){
                [self.delegate socketConnect];
            }
            
        } else if (_socket.readyState == SR_CONNECTING) {
            NSLog(@"正在连接中");
            // 每隔2秒检测一次 socket.readyState 状态，检测 10 次左右
            // 只要有一次状态是 SR_OPEN 的就调用 [ws.socket send:data] 发送数据
            // 如果 10 次都还是没连上的，那这个发送请求就丢失了，这种情况是服务器的问题了，小概率的
            // 代码有点长，我就写个逻辑在这里好了
            
        } else if (_socket.readyState == SR_CLOSING || _socket.readyState == SR_CLOSED) {
            // websocket 断开了，调用 reConnect 方法重连
            if(_isReconnected){
                [self reConnect];
            }
            
        }
    } else {
//        NSLog(@"没网络，发送失败，一旦断网 socket 会被我设置 nil 的");
//        NSLog(@"其实最好是发送前判断一下网络状态比较好，我写的有点晦涩，socket==nil来表示断网");
    }
}


//连接失败的回调
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{
    //    NSLog(@"连接失败，这里可以实现掉线自动重连，要注意以下几点");
    //    NSLog(@"1.判断当前网络环境，如果断网了就不要连了，等待网络到来，在发起重连");
    //    NSLog(@"2.判断调用层是否需要连接，例如用户都没在聊天界面，连接上去浪费流量");
        //关闭心跳包
        if(!_isReconnected){
            //[_socket close];
            _socket = nil;
            
        }else{
            [self reConnect];
        }
        
        
        
        
    }

//连接断开的回调
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
{
    NSLog(@"Close");
    self.isConnected = false;
    self.isReconnected = false;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
{
    NSLog(@"Pong");
}

#pragma mark -- Private Method
//保活机制  探测包
- (void)initHeart{
    __weak typeof(self) weakSelf = self;
    _heatBeat = [NSTimer scheduledTimerWithTimeInterval:60 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf.socket send:@"ping"];
        NSLog(@"ping");
    }];
    [[NSRunLoop currentRunLoop] addTimer:_heatBeat forMode:NSRunLoopCommonModes];
}
//重连机制
- (void)reConnect{
    //每隔一段时间重连一次
    //规定64不在重连,2的指数级
    if (_reConnectTime > 60) {
        return;
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_reConnectTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.socket = nil;
        [self initWebSocket];
        [self.socket open];
    });
    
    if (_reConnectTime == 0) {
        _reConnectTime = 2;
    }else{
        _reConnectTime *= 2;
    }
}
@end
